import axios from "axios";
import { useCounterStore } from "../stores/counter"
import { ElMessage } from "element-plus";

//封装axios
const APIs = axios.create({
    
    baseURL: "http://localhost:5217",
    timeout: 30000  // AI接口需要更长时间，设置为30秒
})
//baseURL
APIs.interceptors.request.use(
    config => {
        const stor = useCounterStore();
        config.headers["Authorization"] = "Bearer " + stor.Users.Token;
        return config;
    },
    error => {
        return Promise.reject(error);
    }
)
APIs.interceptors.response.use(
    res => {
        return res;
    },
    error => {
        if (error.status == 401) {
            ElMessage.error("令牌过期请重新登录");
            setTimeout(() => {
                location.href = "/"
            }, 2000);
        }
        return Promise.reject(error);

    }
)

const ERP = axios.create({
    baseURL: "",
    timeout: 5000
})

// DingDan订单API实例 - 使用不同的端口
const DingDanAPI = axios.create({
    // baseURL: "http://localhost:5199",
    baseURL: "http://101.37.80.143:8088",
    // baseURL: "http://112.124.31.78:1259",
    timeout: 10000
})

// ShenchanInfo生产信息API实例 - 使用5217端口
const ShenchanInfoAPI = axios.create({
    // baseURL: "http://101.37.80.143:8089",
    baseURL: "http://101.37.80.143:8089",
    // baseURL: "http://112.124.31.78:1252",

    timeout: 10000
})

// 为DingDanAPI添加拦截器
DingDanAPI.interceptors.request.use(
    config => {
        const stor = useCounterStore();
        config.headers["Authorization"] = "Bearer " + stor.Users.Token;
        return config;
    },
    error => {
        return Promise.reject(error);
    }
)
DingDanAPI.interceptors.response.use(
    res => {
        return res;
    },
    error => {
        if (error.status == 401) {
            ElMessage.error("令牌过期请重新登录");
            setTimeout(() => {
                location.href = "/"
            }, 2000);
        }
        return Promise.reject(error);
    }
)

// 为ShenchanInfoAPI添加拦截器
ShenchanInfoAPI.interceptors.request.use(
    config => {
        const stor = useCounterStore();
        config.headers["Authorization"] = "Bearer " + stor.Users.Token;
        return config;
    },
    error => {
        return Promise.reject(error);
    }
)
ShenchanInfoAPI.interceptors.response.use(
    res => {
        return res;
    },
    error => {
        if (error.status == 401) {
            ElMessage.error("令牌过期请重新登录");
            setTimeout(() => {
                location.href = "/"
            }, 2000);
        }
        return Promise.reject(error);
    }
)

ERP.interceptors.request.use(
    config => {
        const stor = useCounterStore();
        config.headers["Authorization"] = "Bearer " + stor.Users.Token;
        return config;
    },
    error => {
        return Promise.reject(error);
    }
)
ERP.interceptors.response.use(
    res => {
        return res;
    },
    error => {
        if (error.status == 401) {
            ElMessage.error("令牌过期请重新登录");
            setTimeout(() => {
                location.href = "/"
            }, 2000);
        }
        return Promise.reject(error);

    }
)



// 图片URL拼接工具函数
const getImageUrl = (imageName: string | null | undefined): string => {
    if (!imageName) return '';

    // 如果已经是完整URL，直接返回
    if (imageName.startsWith('http://') || imageName.startsWith('https://')) {
        return imageName;
    }

    // 如果是base64数据，直接返回
    if (imageName.startsWith('data:image/')) {
        return imageName;
    }

    // 图片服务器地址 - 可能与主API不同
    // const imageBaseURL = "http://101.37.80.143:8089"; // 图片服务器地址
    //const imageBaseURL = "http://112.124.31.78:1252"; // 图片服务器地址
    const imageBaseURL = "http://101.37.80.143:8089"; // 图片服务器地址
    
    // 根据上传接口的实际返回格式，图片直接存储在根路径下
    // 直接拼接baseURL和图片文件名
    return `${imageBaseURL}/${imageName}`;
}

// 从完整URL中提取文件路径（保留目录结构）
const extractFileName = (fullUrl: string | null | undefined): string => {
    if (!fullUrl) return '';

    // 如果是base64数据，直接返回
    if (fullUrl.startsWith('data:image/')) {
        return fullUrl;
    }

    // 如果不是HTTP URL，直接返回
    if (!fullUrl.startsWith('http://') && !fullUrl.startsWith('https://')) {
        return fullUrl;
    }

    try {
        // 从URL中提取路径
        const url = new URL(fullUrl);
        let pathname = url.pathname;

        // 移除开头的斜杠
        if (pathname.startsWith('/')) {
            pathname = pathname.substring(1);
        }

        // 调试日志
        // console.log('🔍 extractFileName 调试:', {
        //     原始URL: fullUrl,
        //     完整路径: url.pathname,
        //     处理后路径: pathname,
        //     提取结果: pathname || fullUrl
        // });

        // 返回相对路径（如 Img/xxx.png）
        return pathname || fullUrl;
    } catch (error) {
        // console.warn('无法解析URL:', fullUrl, error);
        return fullUrl;
    }
}

export { APIs, DingDanAPI, ShenchanInfoAPI, getImageUrl, extractFileName }